/**
 * Created by oneminute on 7/17/14.
 */


var http = require("http");
var express = require("express");

//初始化express
var path = require('path');
var domain = require('domain');
var app = express();
var config = require("../config/config");
var logger = require("../lib/utils/logger");
var favicon = require("serve-favicon");
var cookieParser = require('cookie-parser');
var bodyParser = require("body-parser");
var methodOverride = require("method-override");
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
var expressWinston = require('express-winston');
var route = require("../routes/route");

logger.info("服务器(pid: %s)开始启动。", process.pid);

// all environments
app.set('port', process.env.PORT || config.webServer.port);
app.set('views', '../views');
app.set('view engine', 'ejs');

app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(multipartMiddleware);
app.use(express.static('../public'));
app.use(cookieParser());
app.use(expressWinston.logger({
    transports: config.logOptions.transports
}));

route.setup(app);
var httpServer = http.createServer(app);
//chat.setup(httpServer);
httpServer.listen(3000, function(){
    logger.info("服务器(pid:%s)监听端口: %s", process.pid, config.webServer.port);

    var d = domain.create();
    d.on('error', function(err) {
        logger.error("uncaught exception: ", err.stack);
        //关闭服务
        httpServer.close(function(){
            logger.info("close http server.");
            process.disconnect();
        });

        //对于耗时的长连接，设置超时,进程退出
        setTimeout(function(){
            process.kill();
        }, config.webServer.timeout);
    });
});
